package BaseService

import (
	"database/sql"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
	"seawolf-admin-go/internal/request/BaseReq"
	"seawolf-admin-go/utility/db"
	"seawolf-admin-go/utility/response"
)

func Info(r *ghttp.Request, req *BaseReq.I) *response.JsonResponse {
	if len(req.Id) == 0 {
		return response.FailByRequestMessage(r, "id 不能为空")
	}
	ctx := r.GetCtx()
	obj := db.GetUnSafaTable(ctx, req.TableName, req.DbLinkName).WherePri(
		"id",
		req.Id,
	)
	// 过滤字段
	if len(req.InfoIgnoreProperty) > 0 {
		obj.Fields(obj.GetFieldsExStr(req.InfoIgnoreProperty))
	}

	asName := "a"
	infoQueryOp := req.InfoQueryOp
	if infoQueryOp != nil {
		if infoQueryOp.AsName != "" {
			asName = infoQueryOp.AsName
		}
	}
	// 处理查询列条件
	// 有设置表别名
	obj.As(asName)
	// 获取查询条件
	condition := g.Map{}
	GetCondition(r, condition, infoQueryOp, asName)
	obj.Where(
		condition,
	)

	if req.InfoBeforeFn != nil {
		respRes := req.InfoBeforeFn(r)
		if respRes.Code != 0 {
			return respRes
		}
	}
	if req.SoftDeleteField != "" {
		obj.Where(req.SoftDeleteField, 0)
	}
	res, err := obj.One()
	if err != nil {
		if err != sql.ErrNoRows {
			// 非 结果为空
			return response.FailByRequestMessage(r, err.Error())
		}
	}
	if res == nil {
		return response.SuccessByRequestMessageData(r, "没有数据", nil)
	}
	resMap := res.Map()
	if req.InfoAfterFn != nil {
		respData, err := req.InfoAfterFn(r, resMap)
		if err != nil {
			return response.FailByRequestMessage(r, err.Error())
		}
		resMap = respData
	}
	return response.SuccessByRequestMessageData(r, "获取成功",
		resMap)
}
